package com.bingo.sds.controller;

import java.util.Date;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bingo.framework.util.ResultTools;
import com.bingo.sds.entity.User;
import com.bingo.sds.repository.UserRepository;


@RequestMapping(value="/user")
@Controller
public class UserController {
	@Autowired
	private UserRepository repository;
	
	@RequestMapping(value="/saveTest")
	@ResponseBody
	public String saveTest() {
		Long idStart = new Date().getTime();
		for(int i=0; i<5; i++) {
			User user = new User();
			user.setUserId(idStart + i);
			user.setUserName("user"+i);
			repository.save(user);
		}
		
		return ResultTools.successResult("5 records saved");
	}
	
	@GetMapping(value="/getById/{userId}")
	@ResponseBody
	public String saveTest(@PathVariable Long userId) {
		if(userId == null) {
			return ResultTools.errorResult("id cannot be null");
		}
		
		Optional<User> user = repository.findById(userId);
		
		if(user.isPresent()) {
			return ResultTools.dataResult(user.get());
		}
		
		return ResultTools.successResult("no data");
	}
	
	@GetMapping(value="/deleteById/{userId}")
	@ResponseBody
	public String deleteById(@PathVariable Long userId) {
		if(userId == null) {
			return ResultTools.errorResult("id cannot be null");
		}
		
		try {
			repository.deleteById(userId);
		}catch (Exception e) {
			e.printStackTrace();
			return ResultTools.errorResult("Error:"+e.getMessage());
		}
		
		return ResultTools.successResult();
	}
	
	@RequestMapping(value="/saveOrUpdate")
	@ResponseBody
	public String saveOrUpdate(@RequestBody List<User> paramList) {
		if(paramList == null || paramList.isEmpty()) {
			return ResultTools.errorResult("param error");
		}
		
		try {
			repository.saveAll(paramList);
		}catch (Exception e) {
			e.printStackTrace();
			return ResultTools.errorResult("Error:"+e.getMessage());
		}
		
		return ResultTools.successResult();
	}
}
